package com.yww.player

import android.content.Context
import android.os.Environment
import android.provider.MediaStore
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import java.io.File

class VideoListViewModel : ViewModel() {
    var mVideoList = MutableLiveData<ArrayList<VideoModel>>()
    private val TAG = "VideoModel"

    fun searchVideo(context: Context) {
        val tableUrl = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        val projection = arrayOf(
            MediaStore.Video.Media.DISPLAY_NAME,
            MediaStore.Video.Media.SIZE,
            MediaStore.Video.Media.MIME_TYPE,
            MediaStore.Video.Media.DATA
        )
//        开始查询
        val cursor = VrPlayApplication.getAppContext().contentResolver.query(
            tableUrl,
            projection,
            null,
            null,
            null
        );
        val list = arrayListOf<VideoModel>()
        if (cursor != null) {
//           名字下标
            val nameIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME)
//            路径位置
            val pathIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
//            大小
            val sizeIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.SIZE)

            while (cursor.moveToNext()) {
//                名称
                val name = cursor.getString(nameIndex)
                val array = name.split(".")
//                绝对路径
                val path = cursor.getString(pathIndex)
//                大小
                val size = cursor.getString(sizeIndex)
                list.add(VideoModel(name, path, array[1], size, ""))
            }
//            mVideoList.postValue(list)
            cursor.close();
//            val list = File("/sdcard/map4/").listFiles()?.map {
//                VideoModel(it.name, it.absolutePath, "mp4", "0", "")
//            } as ArrayList<VideoModel>
            (File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/mp4")?.listFiles()?.map {
                VideoModel(it.name, it.absolutePath, "", "", "")
            } as? ArrayList<VideoModel>)?.let {
                mVideoList.postValue(it)
            }
        }
    }
}